iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
0
Modern Web

今晚,我想來點Blazor系列 第 14

Day 14:Arbitrary Parameter 任意參數

  • 分享至 

  • xImage
  •  

為什麼需要任意參數?

在前面的Parameter教學中,我們學到要傳參數給子元件,需要在子元件設定一個接收的屬性。

現在我們有一個子元件叫ImgConponent,主要用途很簡單就是用來顯示圖片,所以ImgComponent的程式碼大概會長成下面這個樣子:

<img src="@src" />

@code {
    public string src { get; set; }
}

為了可以重複使用,因此設定一個src的parameter,供呼叫端傳img url進來。

接下來,可能還有個alt屬性要設定,因此我們再加個alt的parameter:

<img src="@src" alt="@alt"/>

@code {
    public string src { get; set; }

    public string alt { get; set; }
}

但我們都知道,Hhtml的img標籤還有很多attribute可以設定,譬如width、heightsrcset等等,如果一個attribute就要搭配一個parameter,這樣會讓我們ImgComponent內有過多屬性,如果今天是Html Input標籤的話,attribute多達30個,那元件裡面就需要增加多達30個paramter,將大幅增加維護上的難度。

這個時候就可用我們今天的主題Arbitrary Parameter任意參數了。
Arbitrary Parameter想做的,就是用一個parameter接收所有的attribute參數。
首先先幫ImgComponent新增一個Dictionary<string,object>的parameter:

<img src="@src"/>

@code {
    [Parameter]
    public string src { get; set; }

    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string,object> AdditionalAttributes { get; set; }
}
  • AdditionalAttributes 是用key-value的方式儲存傳來的attribute
  • 由於現在沒有為每一個attribute指定一個parameter,因此要標註CaptureUnmatchedValues = true,讓Blazor知道只要傳來但沒有相對應parameter的參數,都放到AdditionalAttibutes內。

新增完之後,img標籤的@attibutes設定為AdditionalAttributes :

<img src="@src"  @attributes="AdditionalAttributes">

再來看看怎麼使用這ImgComponent。
使用ImgComponent時,傳attribute有幾個作法:

  1. 直接設定attribute。如果數量少的話,可以直接設定,例如底下只設定alt這一個attribute,可以開F12看到alt是有設定到的。
<ImgComponent src="{srcurl}"
              alt="Captain America laugh" />

https://ithelp.ithome.com.tw/upload/images/20200928/20130058fnSem0EAzj.jpg

如果還要再加,可以接在alt後面繼續加進去,例如:

<ImgComponent src="{imgurl}"
              alt="Captain America laugh" 
              width="100px"
              height="100px"
/>

如果需要設定的attribute較多,可以另外設一個Dictionary<string,object>的變數,再透過@attributes傳給ImgComponent,提升可讀性:

<ImgComponent src="{srcurl}" @attributes="attributes" />

@code{
private Dictionary<string, object> attributes = new Dictionary<string, object>()
{
        { "alt" ,"Captain America laugh"},
        { "width","450px"},
        { "height","300px"}
    };
}

小地方注意

如果子元件有跟呼叫端相同的attribute,例如:

//ImgConmponent
<img src="@src" @attributes="AdditionalAttributes" alt="alt from ImgComponent">

//parent
<ImgComponent src="{imgurl}" alt="alt from Parant" />

這時後面的attribute會覆蓋前面的,看一下結果:
https://ithelp.ithome.com.tw/upload/images/20200928/20130058nwF8LpGadg.jpg

反之,如果ImgComponent將@attributes換一下位子,可以看到傳來的alt覆蓋了ImgComponent的alt:

//ImgConmponent
<img src="@src" alt="alt from ImgComponent" @attributes="AdditionalAttributes" />

//parent
<ImgComponent src="{imgurl}" alt="alt from Parant" />

https://ithelp.ithome.com.tw/upload/images/20200928/20130058Liq7dV2PaE.jpg

以上就是使用Arbitrary Parameter要留意的地方囉!


上一篇
Day 13:Component Parameters
下一篇
Day 15:元件之間的溝通
系列文
今晚,我想來點Blazor30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言